const { categoryConfig } = require('../../../utils/categoryConfig');

Component({
  properties: {},
  data: {
    wordbooks: []
  },
  lifetimes: {
    attached() {
      // 加载用户学习数据
      this.loadUserData();
    }
  },
  methods: {
    onRefresh() {
      this.loadUserData();
    },
    // 获取分类的实际单词数量
    getCategoryWordCount(category) {
      try {
        const dm = getApp().globalData.wordDataManager;
        const words = dm.getWordsByCategory(category);
        return words.length;
      } catch (error) {
        console.error(`获取分类单词数量失败 (${category}):`, error);
        return 0;
      }
    },
    // 获取分类中已学习的单词数量
    getLearnedWordCount(category) {
      try {
        const dm = getApp().globalData.wordDataManager;
        const words = dm.getWordsByCategory(category);
        
        // 统计已学习的单词数量（learnCount > 0 表示已学习）
        const learnedCount = words.filter(word => {
          return dm.getWordLearnedStatus(word.id);
        }).length;
        
        return learnedCount;
      } catch (error) {
        console.error(`获取分类已学习单词数量失败 (${category}):`, error);
        return 0;
      }
    },
    // 打开词书
    openWordbook(e) {
      const wordbookId = e.currentTarget.dataset.id;
      const wordbook = this.data.wordbooks.find(book => book.id === wordbookId);
      
      wx.navigateTo({
        url: `/pages/vocabulary/word-list/word-list?category=${encodeURIComponent(wordbook.category)}`
      });
    },
    // 加载用户学习数据
    loadUserData() {
      // 使用共享的分类配置作为基础数据
      // 更新词书实际单词数量和已学习单词数量
      const updatedWordbooks = categoryConfig.map(book => {
        // 获取该分类的实际单词数量
        const actualWordCount = this.getCategoryWordCount(book.category);
        // 获取该分类的已学习单词数量
        const learnedWordCount = this.getLearnedWordCount(book.category);
        // 计算进度百分比
        const progress = actualWordCount > 0 ? Math.round((learnedWordCount / actualWordCount) * 100) : 0;
        
        return {
          ...book,
          // 使用实际单词数量作为totalWords
          totalWords: actualWordCount || 0,
          // 设置已学习单词数量
          learnedWords: learnedWordCount,
          // 设置进度百分比
          progress: progress
        };
      });
      
      this.setData({
        wordbooks: updatedWordbooks
      });
    }
  }
});
